# -*- coding:utf-8 -*-


"""

    Xi Gua video Million Heroes

"""

from core.android import capture_screen, analyze_picture_text
from core.android import save_screen


import thread
import multiprocessing
import random
from multiprocessing import Event
from multiprocessing import Pipe
import time
from argparse import ArgumentParser

import operator
from functools import partial

import os

from terminaltables import AsciiTable

from config import api_key, crop_areas_qeustion, crop_areas_answers, wait_times
from config import api_version, app_id, app_key, app_secret, data_directory
from config import enable_chrome, image_compress_level, prefer
from config import auto_test, test_count, crop_areas_answers_item, answer_engine

from core.baiduzhidao import baidu_count, wukong_count, _360_count, bing_count, sougou_count
from core.check_words import parse_false
from core.chrome_search import run_browser
from core.ocr.baiduocr import get_text_from_image as bai_get_text
from core.ocr.spaceocr import get_text_from_image as ocrspace_get_text

from colorama import Fore

from PIL import Image

if prefer[ 0 ] == "baidu":
    get_text_from_image = partial(bai_get_text,
                                  app_id=app_id,
                                  app_key=app_key,
                                  app_secret=app_secret,
                                  api_version=api_version,
                                  timeout=5)

elif prefer[ 0 ] == "ocrspace":
    get_test_from_image = partial(ocrspace_get_text, api_key=api_key)


def parse_args():
    parser = ArgumentParser(description="Million Hero Assistant")
    parser.add_argument(
        "-t", "--timeout",
        type=int,
        default=5,
        help="default http request timeout"
    )
    return parser.parse_args()


def parse_question_and_answer(text_list):
    question = ""
    start = 0
    for i, keyword in enumerate(text_list):
        question += keyword
        if "?" in keyword:
            start = i + 1
            break
    real_question = question.split(".")[ -1 ]
    question, true_flag = parse_false(real_question)
    return true_flag, real_question, question, text_list[ start: ]

def pre_process_answers(keywordsa):
    newanswers = []
    for answer in keywordsa:
        nw = pre_process_answer(answer)
        newanswers.append(nw)

    return newanswers


def pre_process_answer(keyword):
    """
    strip charactor and strip ?
    :param question:
    :return:
    """
    from datetime import datetime
    now = datetime.today()
    for char, repl in [ ("“", ""), ("”", ""),
                        ("？", ""), ("?", ""),
                        ("《", ""), ("》", ""), ("\"", ""),
                        ("我国", "中国"),
                        ("今天", "{0}年{1}月{2}日".format(now.year, now.month, now.day)),
                        ("今年", "{0}年".format(now.year)),
                        ("这个月", "{0}年{1}月".format(now.year, now.month)) ]:
        keyword = keyword.replace(char, repl)

    keyword = keyword.split(r"．")[ -1 ]
    return keyword

def pre_process_question(keyword):
    """
    strip charactor and strip ?
    :param question:
    :return:
    """
    from datetime import datetime
    now = datetime.today()
    for char, repl in [("“", " "), ("”", " "),
                       ("？", ""), ("?", ""),
                       ("《", " "), ("》", " "), ("\"", " "),
                       ("我国", "中国"),
                       ("今天", "{0}年{1}月{2}日".format(now.year, now.month, now.day)),
                       ("今年", "{0}年".format(now.year)),
                       ("这个月", "{0}年{1}月".format(now.year, now.month))]:
        keyword = keyword.replace(char, repl)
        
    keyword = keyword.split(r"．")[-1]
    #keywords = keyword.split(" ")
    #keyword = "".join([e.strip("\r\n") for e in keywords if e])
    return keyword

def outputAnseres(summary, true_flag):
    sis = summary.items()
    data = [ ("选项", "同比") ]
    for a, w in sis:
        data.append((a, w))
    table = AsciiTable(data)
    print(table.table)

    summary_li = sorted(
        summary.items(), key=operator.itemgetter(1), reverse=True)

    print("*" * 72)
    if true_flag:
        print("肯定回答(**)： " + Fore.LIGHTYELLOW_EX + summary_li[ 0 ][ 0 ] + Fore.RESET)
        print("否定回答(  )： " + summary_li[ -1 ][ 0 ])
    else:
        print("肯定回答(  )： " + summary_li[ 0 ][ 0 ])
        print("否定回答(**)： " + Fore.LIGHTYELLOW_EX + summary_li[ -1 ][ 0 ] + Fore.RESET)
    print("*" * 72)

def fix_answer(summary):
    keys = summary.keys()
    keys = list(map(str, keys))

    len = keys.__len__()

    for i in (0, len - 2):
        for j in (i + 1, len - 1):
            if keys[i] in keys[j]:
                summary[keys[i]] = summary[keys[i]] - summary[keys[j]]
            elif keys[j] in keys[i]:
                summary[keys[j]] = summary[keys[j]] - summary[keys[i]]

    return summary

def outputAnseresEx(summary, true_flag):
    keys = summary.keys()
    keys = list(map(str, keys))

    values = summary.values()
    counts = list(map(int, values))
    index_max = counts.index(max(counts))
    index_min = counts.index(min(counts))

    if index_max == index_min:
        print(Fore.RED + "答题失败！随机给出答案" + Fore.RESET)
        index_max = random.randint(0, 2)

    print("=" * 36)
    for i in range(len(keys)):
        if i == index_max:
            if true_flag:
                # 绿色为计数最高的答案
                print(Fore.LIGHTYELLOW_EX + "{0:<5}: {1} ".format(counts[i], keys[i]) + Fore.RESET)
            else:
                print(Fore.LIGHTRED_EX + "{0:<5}: {1} ".format(counts[i], keys[i]) + Fore.RESET)
        elif i == index_min:
            if true_flag:
                # 红色为计数最低的答案
                print(Fore.LIGHTRED_EX + "{0:<5}: {1}".format(counts[i], keys[i]) + Fore.RESET)
            else:
                print(Fore.LIGHTYELLOW_EX + "{0:<5}: {1}".format(counts[i], keys[i]) + Fore.RESET)
        else:
            print("{0:<5}: {1}".format(counts[i], keys[i]))

    print("=" * 36)

    if true_flag:
        return index_max
    else:
        return index_min


def touch_item(type, index, width, height):
    if index > 3:
        return

    coor = crop_areas_answers_item[ type ]
    cmd = 'adb shell input swipe {x1} {y1} {x2} {y2}'.format(
        x1=width / 2,
        y1=height * coor[index],
        x2=width / 2,
        y2=height * coor[index],
    )
    os.system(cmd)


# LIGHTMAGENTA_EX 紫色
# LIGHTBLUE_EX 蓝色
# LIGHTRED_EX 红色
# LIGHTYELLOW_EX 黄色


def swipe_to_next_pic():
    cmd = 'adb shell input swipe {x1} {y1} {x2} {y2}'.format(
        x1=600, y1=200, x2=200, y2=200)
    os.system(cmd)


def auto_answer(game_type, width, height):
    t = wait_times[game_type] + 0.5
    time.sleep(t)
    answerindex = random.randint(0, 2);
    if game_type == '百万大脑':
        answerindex = random.randint(0, 3);
    touch_item(game_type, answerindex, width, height)

def __inner_job_my(game_type, writer, noticer, timeout):
    start = time.time()
    capture_screen(directory=data_directory)
    screenshot_filename = os.path.join(data_directory, "screenshot.png")
    image = Image.open(screenshot_filename)

    width, height = image.size[0], image.size[1]
    thread.start_new_thread(auto_answer, (game_type, width, height))

    print()
    text_binary_q = analyze_picture_text(
        image = image, dst_file_name=os.path.join(data_directory,"text_area_q.png"),
        compress_level=image_compress_level[ 0 ],
        crop_area=crop_areas_qeustion[ game_type ])
    keywordsq = get_text_from_image(image_data=text_binary_q, )

    if not keywordsq:
        print(Fore.LIGHTRED_EX + "问题识别失败！" + Fore.RESET)
        return

    all_question = "".join(keywordsq)
    real_question = all_question.split(".")[ -1 ]

    print(all_question)
    question, true_flag = parse_false(real_question)
    search_question = pre_process_question(question)

    # notice browser
    if enable_chrome:
        writer.send(search_question)
        noticer.set()

    text_binary_a = analyze_picture_text(
        image=image,
        dst_file_name=os.path.join(data_directory, "text_area_a.png"),
        compress_level=image_compress_level[ 0 ],
        crop_area=crop_areas_answers[ game_type ]
    )

    keywordsa = get_text_from_image(image_data=text_binary_a)
    if not keywordsa:
        print(Fore.LIGHTRED_EX + "答案识别失败！" + Fore.RESET)
        return

    keywordsa = pre_process_answers(keywordsa)

    if answer_engine == 0:
        summary = baidu_count(search_question, keywordsa, timeout=timeout)
    elif answer_engine == 1:
        summary = wukong_count(search_question, keywordsa, timeout=timeout)
    elif answer_engine == 2:
        summary = _360_count(search_question, keywordsa, timeout=timeout)
    elif answer_engine == 3:
        summary = bing_count(search_question, keywordsa, timeout=timeout)
    elif answer_engine == 4:
        summary = sougou_count(search_question, keywordsa, timeout=timeout)
    else:
        summary = baidu_count(search_question, keywordsa, timeout=timeout)

    summary = fix_answer(summary)

    answerindex = outputAnseresEx(summary, true_flag)
    # outputAnseres(summary, true_flag)

    if answerindex > 3:
        answerindex = 2

    end = time.time()
    print("答案：" + Fore.LIGHTYELLOW_EX + " {0}".format(answerindex) +
          Fore.RESET + " , 耗时: {0:.2f} ".format(end - start))

    if wait_times.__contains__(game_type):
        remain = wait_times[game_type] - end + start
    else:
        remain = wait_times['默认游戏'] - end + start

    if remain > 0:
        print("++小憩{0:.2f}秒后自动答题！++".format(remain))
        time.sleep(remain)

    touch_item(game_type, answerindex, width, height)
    save_screen(directory=data_directory)

    if auto_test:
        print("自动测试，进行下一题！")
        swipe_to_next_pic()

"""
    import numpy as np
    from skimage import morphology
    image = image.convert("L")
    array_img = np.array(image)
    ot_img = (array_img > 225)
    obj_dtec_img = morphology.remove_small_objects(ot_img, min_size=width * height / 4, connectivity=1)
    if np.sum(obj_dtec_img) < 1000:
        return False
    region = image.crop((
        np.where(obj_dtec_img * 1.0 > 0)[ 1 ].min(),
        np.where(obj_dtec_img * 1.0 > 0)[ 0 ].min() + 155,
        np.where(obj_dtec_img * 1.0 > 0)[ 1 ].max(),
        np.where(obj_dtec_img * 1.0 > 0)[ 0 ].max()))
    region.save("ttttt.png")
"""

def printInfo():
    print("请选择答题节目:")
    print("\t1. 百万英雄")
    print("\t2. 冲顶大会")
    print("\t3. 芝士超人")
    print("\t4. 百万大脑")

    game_type = input("输入节目序号: ")
    if game_type == "1":
        game_type = '百万英雄'
    elif game_type == "2":
        game_type = '冲顶大会'
    elif game_type == "3":
        game_type = "芝士超人"
    elif game_type == '4':
        game_type = "百万大脑"
    else:
        game_type = '百万英雄'

    return game_type


def main():
    args = parse_args()
    timeout = args.timeout



    if enable_chrome:
        closer = Event()
        noticer = Event()
        closer.clear()
        noticer.clear()
        reader, writer = Pipe()
        browser_daemon = multiprocessing.Process(
            target=run_browser, args=(closer, noticer, reader,))
        browser_daemon.daemon = True
        browser_daemon.start()

    game_type = printInfo()

    #touch_item(game_type, 0, 1080, 2160)
    #touch_item(game_type, 1, 1080, 2160)
    #touch_item(game_type, 2, 1080, 2160)

    index = 0
    while True:
        if auto_test:
            if index >= test_count:
                break
        else:
            enter = input("Enter开始，S + Enter 切换游戏")
            if enter == chr(27):
                break
            elif enter == 's' or enter == 'S':
                game_type = printInfo()
        try:
            __inner_job_my(game_type, writer, noticer, timeout)
        except Exception as e:
            print(str(e))

        index += 1

    if enable_chrome:
        reader.close()
        writer.close()
        closer.set()
        time.sleep(3)


if __name__ == "__main__":
    main()


def test(summary):
    keys = summary.keys()
    keys = list(map(str, keys))

    for i in (0, keys.count() - 1):
        for j in (i + 1, keys.count()):
            if keys[i] in keys[j]:
                summary[keys[i]] = summary[keys[i]] - summary[keys[j]]
            elif keys[j] in keys[i]:
                summary[keys[j]] = summary[keys[j]] - summary[keys[i]]
                return